package com.ht.api.request.report;

import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.DbPage;
import com.ht.api.db.Entity;
import com.ht.api.db.annotate.FuncCall;
import com.ht.api.db.annotate.FuncGroup;
import com.ht.api.db.annotate.FuncId;
import com.ht.api.db.annotate.FuncName;
import com.ht.api.db.annotate.FuncParam;
import com.ht.api.db.annotate.FuncParams;
import com.ht.api.db.bean.DataResult;
import com.ht.api.db.bean.SessionBean;
import com.ht.api.db.enums.Param;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.request.IHandleRequest;
import com.ht.api.db.util.RedisUtil;
import com.ht.api.service.report.ReportService;
import com.ht.api.util.CallTestUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;

@Slf4j
@FuncId("1914141839523450880")
@FuncGroup("报表相关")
@FuncParams({
	@FuncParam(name = "报表key", code = "key", value = "UserOrderPriceReport"),
})

@FuncCall
@FuncName("通用报表")
public class ReportCall implements IHandleRequest {

	@Override
	public void execute(SessionBean me, JSONObject param, DataResult result) {
		// 根据key查找相应的report
		String key = param.getStr("key");
		Entity report = RedisUtil.get("report:" + key);
		if (report == null) {
			throw new HtException("报表不存在，key:" + key);
		}

		boolean isconfig = report.getInt("type") == 1 ? true : false;

		if (isconfig) {
			DbList list = configToReport(me.getDataSource(), report, param);
			result.set(list);
		} else {
			sqlToReport(me.getDataSource(), param, report, result);
		}

	}

	public DbList configToReport (DataSource ds, Entity report, JSONObject param) {
		JSONObject config = report.getJSONObject("config");

		DbList list = ReportService.parseConfigSql(ds, config, param);

		return list;
	}

	public void sqlToReport (DataSource ds, JSONObject param, Entity report, DataResult result) {
		// 获取报表的sql
		JSONObject condition = param.getJSONObject("condition");
		String sql = report.getStr("sql");

		// 将sql转为小写，以防万一
		sql = sql.toLowerCase();

		// 1. 组装前端的order
		sql = ReportService.appendOrder(sql, param.getJSONArray("order"));

		// 2. 替换sql变量
		String newSql = ReportService.filterSql(ds, sql, param);

		// 3. 组装前端的Limit
		String listSql = ReportService.appendLimit(newSql, param.getJSONObject("limit"));
		DbList dbList = Db.query(ds, listSql);

		// 总记录数（有分页时，才查总记录数）
		Long total = null;
		Integer pageNum = null;
		Integer pageSize = null;
		JSONObject limit = param.getJSONObject("limit");
		if (limit != null) {
			pageNum = limit.getInt("pagenum");
			pageSize = limit.getInt("pagesize");
			if (pageNum != null) {
				String countSql = String.format("select count(*) from (%s)sub_query", newSql);
				total = Db.count(ds, countSql);
			}
		}

		// 3. 封装分页结果
		DbPage dbPage = DbPage.builder()
				.pagenum(pageNum)
				.pagesize(pageSize)
				.total(total)
				.record(dbList)
				.build();
		result.set(dbPage);
	}

	public static void main(String[] args) {
		//System.err.println("@FuncId>>" + HtUtil.getId());

		JSONObject result = CallTestUtil.autoTest(new Object(){}.getClass().getEnclosingClass().getSimpleName());
//		System.err.println(result.toStringPretty());
	}


}
